package com.grademaster.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.grademaster.common.R;
import com.grademaster.dto.StudentDto;
import com.grademaster.dto.StudentPageDto;
import com.grademaster.entity.StudentInfo;
import com.grademaster.mapper.StudentInfoMapper;
import com.grademaster.service.StudentInfoService;
import com.grademaster.util.LoginUtil;
import com.grademaster.vo.StudentVO;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;

/**
 * @author Administrator
 * @description 针对表【student_info(学生信息表)】的数据库操作Service实现
 * @createDate 2024-06-26 16:19:09
 */
@Service
public class StudentInfoServiceImpl extends ServiceImpl<StudentInfoMapper, StudentInfo>
        implements StudentInfoService {

    @Autowired
    private StudentInfoMapper studentInfoMapper;

    /**
     * 根据分页条件查询学生信息
     *
     * @param studentPageDto
     * @return
     */
    @Override
    public R getAllStudentsByPage(StudentPageDto studentPageDto) {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()) {
            return R.error("权限不足");
        }
        List<StudentVO> voList = studentInfoMapper.selectStudentClassInfoByCondition(studentPageDto.getClassName()
                , studentPageDto.getUsername()
                , studentPageDto.getName()
                , studentPageDto.getPage()
                , studentPageDto.getPageSize());
        int count = studentInfoMapper.countStudentClassInfoByCondition(studentPageDto.getClassName()
                , studentPageDto.getUsername()
                , studentPageDto.getName());
        Page<StudentVO> page = new Page<>(studentPageDto.getPage(), studentPageDto.getPageSize(),count);
        page.setRecords(voList);
        return R.success(page);
    }
    /**
     * 新增学生信息
     *
     * @param studentPageDto
     * @return
     */
    @Override
    public ResponseEntity exportExcel(StudentPageDto studentPageDto) {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()) {
            return ResponseEntity.badRequest().build();
        }
        List<StudentVO> voList = studentInfoMapper.selectStudentClassInfoByCondition(studentPageDto.getClassName()
                , studentPageDto.getUsername()
                , studentPageDto.getName()
                , 1
                , 2000);
        Workbook workbook = new XSSFWorkbook();

        // Create a sheet named "Students"
        Sheet sheet = workbook.createSheet("Students");

        // Create header row
        Row headerRow = sheet.createRow(0);
        String[] headers = {"学生信息id", "班级名称", "学生学号", "学生姓名"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // Create data rows
        int rowNum = 1;
        for (StudentVO student : voList) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(student.getStudentInfoId());
            row.createCell(1).setCellValue(student.getClassName());
            row.createCell(2).setCellValue(student.getUsername());
            row.createCell(3).setCellValue(student.getName());
        }

        // Auto-size columns (optional)
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }

        // Write workbook to ByteArrayOutputStream
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // Create InputStreamResource to wrap ByteArrayInputStream
        ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        InputStreamResource resource = new InputStreamResource(inputStream);

        // Set response headers
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=students.xlsx");

        // Return ResponseEntity with Excel file as body
        return ResponseEntity.ok()
                .headers(httpHeaders)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }

    /**
     * 根据学生id查询学生信息
     *
     * @param studentDto
     * @return
     */
    @Override
    public R editStudentClass(StudentDto studentDto) {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()) {
            return R.error("权限不足");
        }
        StudentInfo studentInfo = studentInfoMapper.selectById(studentDto.getStudentInfoId());
        studentInfo.setClassId(studentDto.getClassId());
        studentInfoMapper.updateById(studentInfo);
        return R.success("修改成功");
    }


}




